<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Madmins extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
	
	/*
	* Admin system
	*/
	
    public function getListAdminSystem($number = 0,$offset = 0){
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT * FROM user WHERE level = 1 ";
        $count = $this->db->query($sql)->num_rows();
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        return array('data' => $xs, 'count' => $count);
    }
    
    public function getAdminSystemDetail($id){
        $sql = "SELECT * FROM user WHERE id = ".$id;
        $data = $this->db->query($sql)->row_object();
        return $data;
    }
    
    public function addAdminsystem($data){
        if( $this->db->query('SELECT id FROM user WHERE username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		$data['password'] = md5(md5($data['username']).md5($data['password']));
		$data['created'] = date('Y-m-d H:i:s');
		$data['level'] = $data['active'] = 1;
        $this->db->insert('user', $data);
        return 200;
    }
    
    public function editAdminsystem($id,$data,$password){
		if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		if( !in_array($password,array('',null)) ){
			$data['password'] = md5(md5($data['username']).md5($password));
		}
        $this->db->update('user', $data, "id = ".$id);
        return 200;
    } 
    
    public function deleteAdminSystem($id){
		if( $id == 1 ){ return 201; }
        $this->db->delete('user', "id = ".$id);
        return 200;
    }
	
	
	/*
	* Admin group
	*/
	
    public function getListAdminGroup($number = 0,$offset = 0){
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT u.* FROM user AS u WHERE u.level = 2 ";
        $count = $this->db->query($sql)->num_rows();
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        foreach($xs AS $key => $val){
            $xs[$key]->group = $this->db->query("SELECT name FROM tbl_group AS tg LEFT JOIN manage_group_key AS gk ON gk.group_id = tg.id WHERE gk.user_id = ".$val->id)->result_object();
        }
        return array('data' => $xs, 'count' => $count);
    }
	
	public function getAdminGroupDetail($id){
        $sql = "SELECT * FROM user WHERE id = ".$id;
        $data = $this->db->query($sql)->row_object();
        return $data;
    }
	
	public function getGroup(){
	    if($this->session->userdata('level') == 2){
           return $this->db->query('SELECT tg.id, tg.name FROM tbl_group AS tg LEFT JOIN manage_group_key AS gk ON gk.group_id = tg.id WHERE gk.user_id = '.$this->session->userdata('id'))->result_object();
	    }
		return $this->db->query('SELECT id, name FROM tbl_group WHERE 1=1')->result_object();
	}
	
	public function addAdminGroup($data,$arr_group_id){
        if( $this->db->query('SELECT id FROM user WHERE username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		$data['password'] = md5(md5($data['username']).md5($data['password']));
		$data['created'] = date('Y-m-d H:i:s');
		$data['level'] = 2;
		$data['active'] = 1;
        $this->db->insert('user', $data);
        
        $this->insertKeyGroup($this->db->insert_id(),$arr_group_id);
        return 200;
    }
	
    public function getListGroupManaged($id){
        $sql = "SELECT group_id FROM manage_group_key WHERE user_id = ".$id;
        $data = $this->db->query($sql)->result_object();
        $arr = array();
        foreach($data AS $key => $val){
            $arr[] = $val->group_id;
        }
        return $arr;
    }
	
    public function editAdminGroup($id,$data,$password,$arr_group_id){
		if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		if( !in_array($password,array('',null)) ){
			$data['password'] = md5(md5($data['username']).md5($password));
		}
		//echo '<pre>';die(print_r($data));
        $this->db->update('user', $data, "id = ".$id);
        $this->deleteKeyGroup($id);
        $this->insertKeyGroup($id,$arr_group_id);
        return 200;
    } 
    
    public function deleteAdminGroup($id){
		if( $id == 1 ){ return 201; }
        $this->db->delete('user', "id = ".$id);
        
        $this->deleteKeyGroup($id);
        return 200;
    }
    
    private function insertKeyGroup($user_id,$arr_group_id)
    {
        foreach($arr_group_id AS $key => $value){
            $arr = array(
                'user_id' => $user_id,
                'group_id' => $value
            );
            $this->db->insert('manage_group_key', $arr);
        }
        return 200;
    }
    private function deleteKeyGroup($user_id)
    {
        $this->db->delete('manage_group_key', "user_id = ".$user_id);
        return 200;
    }
	
	
	/*
	* Admin device 
	*/
	
	
	 public function getListAdminDevice($number = 0,$offset = 0){
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT u.*, tg.name AS group_name FROM user AS u 
        LEFT JOIN manage_device_key AS dk ON dk.user_id = u.id 
        LEFT JOIN tbl_group AS tg ON tg.id = dk.group_id 
        WHERE u.level = 3";
		if( $this->session->userdata('level') == 2 ){
		  
			$sql .= " AND dk.group_id IN (SELECT DISTINCT group_id FROM manage_group_key WHERE user_id = ".$this->session->userdata('id').")";
		}
        $sql .= " GROUP BY u.id";
        $count = $this->db->query($sql)->num_rows();
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        foreach($xs AS $key => $val){
            $xs[$key]->device = $this->db->query("SELECT td.namedevice FROM tbl_device AS td LEFT JOIN manage_device_key AS dk ON dk.device_id = td.id WHERE dk.user_id = ".$val->id)->result_object();
        }
        //die($sql);
        //echo "<pre>"; print_r($xs);die;
        
        return array('data' => $xs, 'count' => $count);
    }
	
	public function getDevice($id = 0,$group = 0){
	   
        if(!in_array($id, array(null, '', '0'))){
            $sql = 'SELECT * FROM tbl_device WHERE tbl_device.id NOT IN (SELECT DISTINCT device_id FROM manage_device_key WHERE user_id != '.$id.')';
        }else{
            $sql = 'SELECT * FROM tbl_device WHERE tbl_device.id NOT IN (SELECT DISTINCT device_id FROM manage_device_key)';
        }
        
        if(!in_array($group, array(null, '', '0'))){
            $sql .= ' AND network_group = '.$group;
        }
        
        //die($sql);
        
		/*if( $this->session->userdata('level') == 2 ){
			$sql .= ' AND network_group = '.$this->session->userdata('manage_group_id').' ';
		}*/
        
        //echo "<pre>";
        //die(print_r($this->db->query($sql)->result_object()));
		return $this->db->query($sql)->result_object();
	}
	
	public function addAdminDevice($data,$arr_device_id){
        if( $this->db->query('SELECT id FROM user WHERE username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		$data['password'] = md5(md5($data['username']).md5($data['password']));
		$data['created'] = date('Y-m-d H:i:s');
		$data['level'] = 3;
		$data['active'] = 1;
        $this->db->insert('user', $data);
        $id_user = $this->db->insert_id();
		$this->insertKeyDevice($id_user,$arr_device_id,$data['manage_group_id']);
        
        if($this->getParamInt('sync') == 1){
            $this->addAdminWicity($id_user,$data,$arr_device_id);
        }
        return 200;
    }
    
    /**
     * @void Fn sync insert to project Wicity 
     * -------------------------------------------------
     */ 
    private function addAdminWicity($id_cpanel,$data,$arr_device_id){
        
        /**
         * @void add user
         */ 
        $arr = array(
                'username'         => $data['username'],
                'pword'            => $data['password'],
                'fullname'         => $data['fullname'],
                'email'            => $data['email'],
                'mobile'           => $data['mobile'],
                'active'           => 1,
                'admin_id'         => $admin_id,
                'level'            => 4,
                'created'          => date('Y-m-d H:i:s'),
                'percentage'       => 0,
                'type_percentage'  => 1
            );
            
        if($data['manage_group_id'] == 2){ //Điểm vệ tinh => supplier 2
            $arr['is_supplier2'] = 1;
        }
            
        $arr['user_cpanel_sync'] = $id_cpanel;
        
        $this->db_b = $this->load->database('wicitydb', TRUE);
        
        $this->db_b->insert('user', $arr);
        $id_user = $this->db_b->insert_id();
        
        //Đồng bộ sang Menu
        unset($arr['user_cpanel_sync']);
        $this->syncInsertUserMenuProject($arr, $id_user);
        
        
        /**
         * @void place_account
         */ 
        $count_p = 1;
        $device_in = '(';
        foreach($arr_device_id AS $key => $value){
            if($count_p == count($arr_device_id)){
                $device_in .= ' '.$value;
            }else{
                $device_in .= ' '.$value.',';
            }
            $count_p++;
        }
        $device_in .= ' )';
        
        //Lấy danh sách id address sync
        $address_sync = $this->db->query("SELECT a.id,d.nasid FROM tbl_address AS a LEFT JOIN tbl_device AS d ON d.id_address = a.id WHERE d.id IN ".$device_in)->result_object();
        
        foreach($address_sync AS $key => $value){
            $_address_id = array();
            
            if(!in_array($value->id, $_address_id)){ // Check trùng key địa điểm
                $_address_id[] = $value->id;
            
                //Lấy id address wicity
                $place = $this->db_b->query("SELECT p.id FROM place AS p WHERE p.id_address_sync = ".$value->id)->row_object();
                //Add place_account với id_user vừa tạo
                $this->db_b->insert('place_account', array('id_user' => $id_user, 'id_place' => $place->id));
                $this->syncInsertUserMenuPlace($place->id, $id_user);
            }
            
            /**
             * @void update modem
             */ 
             
            $arr = array(
                'id_place' => $place->id
            );
            $this->db_b->update('modem', $arr, "nas_id = '".$value->nasid."'");
        }
        
        $arr_ = array( 'id_user' => $id_user, 'id_gr' => 4, 'created' => date('Y-m-d H:i:s') );
        $this->db_b->insert('permission_account',$arr_);
        
        return 200;
    }
    
    /**
     * @void Fn sync insert to project Menu
     * -------------------------------------------------
     */
    private function syncInsertUserMenuProject($data, $id_user)
    {
        $data['id_sync'] = $id_user;
        $this->db_c = $this->load->database('menudb', TRUE);
        $this->db_c->insert('user', $data);
    }
    
    private function syncInsertUserMenuPlace($id_place, $id_user)
    {
        $this->db_c = $this->load->database('menudb', TRUE);
        $this->db_c->insert('setting_restaurent', array('id_restaurent' => $id_place, 'id_admin' => $id_user, 'created' => date('Y-m-d H:i:s')));
    }
		
	public function getlistdevice(){
		$id = $this->getParamInt('id');
		$data = $this->db->query('SELECT * FROM tbl_device WHERE id NOT IN (SELECT device_id FROM manage_device_key) AND network_group = '.$id)->result_object();
		return $data;
	}
    
    public function getAdminDeviceDetail($id){
        $sql = "SELECT u.* FROM user AS u WHERE u.id = ".$id;
        $data = $this->db->query($sql)->row_object();
        return $data;
    }
    
    public function getListDeviceManaged($id){
        $sql = "SELECT td.id FROM tbl_device AS td LEFT JOIN manage_device_key AS dk ON dk.device_id = td.id WHERE dk.user_id = ".$id;
        $data = $this->db->query($sql)->result_object();
        $arr = array();
        foreach($data AS $key => $val){
            $arr[] = $val->id;
        }
        return $arr;
    }
    
    public function editAdminDevice($id,$data,$password,$arr_device_id){
        if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND username = "'.$data['username'].'" ')->num_rows() > 0 ){
			return 201;
		}
		if( $this->db->query('SELECT id FROM user WHERE id != '.$id.' AND email = "'.$data['email'].'" ')->num_rows() > 0 ){
			return 202;
		}
		if( !in_array($password,array('',null)) ){
			$data['password'] = md5(md5($data['username']).md5($password));
		}
		//echo '<pre>';die(print_r($data));
        $this->db->update('user', $data, "id = ".$id);
        $this->deleteKeyDevice($id);
        $this->insertKeyDevice($id,$arr_device_id,$data['manage_group_id']);
        
        if($this->getParamInt('sync') == 1){
            $this->editAdminWicity($id,$data,$arr_device_id);
        }
        return 200;
    }
    
    /**
     * @void Fn sync update to project Wicity 
     * -------------------------------------------------
     */ 
    private function editAdminWicity($id_cpanel,$data,$arr_device_id){
        /**
         * @void edit user
         */ 
        $arr = array(
                'username'         => $data['username'],
                'pword'            => $data['password'],
                'fullname'         => $data['fullname'],
                'email'            => $data['email'],
                'mobile'           => $data['mobile']
            );
            
        if($data['manage_group_id'] == 2){ //Điểm vệ tinh => supplier 2
            $arr['is_supplier2'] = 1;
        }
            
        $this->db_b = $this->load->database('wicitydb', TRUE);
        $id_user = $this->db_b->query("SELECT id FROM user WHERE user_cpanel_sync = ".$id_cpanel)->row_object()->id;
        
        if(in_array($id_user, array(null, '', '0'))){
            $this->addAdminWicity($id_cpanel,$data,$arr_device_id);
            return 200;
        }else{
            $this->db_b->update('user', $arr, "user_cpanel_sync = ".$id_cpanel);
        }
        
        //xóa bản ghi cũ trong place_account
        $this->db_b->delete('place_account', "id_user = ".$id_user);
        
        /**
         * @void place_account
         */ 
        $count_p = 1;
        $device_in = '(';
        foreach($arr_device_id AS $key => $value){
            if($count_p == count($arr_device_id)){
                $device_in .= ' '.$value;
            }else{
                $device_in .= ' '.$value.',';
            }
            $count_p++;
        }
        $device_in .= ' )';
        
        //Lấy danh sách id address sync
        $address_sync = $this->db->query("SELECT a.id,d.nasid FROM tbl_address AS a LEFT JOIN tbl_device AS d ON d.id_address = a.id WHERE d.id IN ".$device_in)->result_object();
        
        foreach($address_sync AS $key => $value){
            $_address_id = array();
            
            if(!in_array($value->id, $_address_id)){ // Check trùng key địa điểm
                $_address_id[] = $value->id;
            
                //Lấy id address wicity
                $place = $this->db_b->query("SELECT p.id FROM place AS p WHERE p.id_address_sync = ".$value->id)->row_object();
                //Add place_account với id_user vừa tạo
                $this->db_b->insert('place_account', array('id_user' => $id_user, 'id_place' => $place->id));
                
            }
            
            /**
             * @void update modem
             */ 
             
            $arr = array(
                'id_place' => $place->id
            );
            $this->db_b->update('modem', $arr, "nas_id = '".$value->nasid."'");
        }
    }
    
    public function deleteAdminDevice($id){
		if( $id == 1 ){ return 201; }
        $this->db->delete('user', "id = ".$id);
        
        $this->deleteKeyDevice($id);
        return 200;
    }
	
    private function insertKeyDevice($user_id,$arr_device_id,$group_id)
    {
        foreach($arr_device_id AS $key => $value){
            $arr = array(
                'user_id' => $user_id,
                'device_id' => $value,
                'group_id' => $group_id
            );
            $this->db->insert('manage_device_key', $arr);
        }
        return 200;
    }
    
    private function deleteKeyDevice($user_id)
    {
        $this->db->delete('manage_device_key', "user_id = ".$user_id);
        return 200;
    }
}
